package com.ls.product.controller;

import com.ls.common.annotation.Idempotent;
import com.ls.common.entity.PageData;
import com.ls.common.entity.Result;
import com.ls.common.util.TokenUtil;
import com.ls.product.pojo.dto.PageProductDTO;
import com.ls.product.service.IProductService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.ls.product.pojo.entity.Product;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaotang
 * @since 2023-04-07
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    IProductService productService;

    @Value("${spring.cloud.client.ip-address}")
    private String host;

    @Value("${server.port}")
    private String port;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/{id}")
    public Result<Product> getProduct(@PathVariable Integer id){
        Product data = productService.getById(id);
        return new Result(200, host + ":" + port, data);
    }

    @PutMapping("addOrUpdateProduct")
    @ApiOperation("添加或者修改产品")
    public Result addOrUpdateProduct(@RequestBody Product product){
        boolean flag = productService.saveOrUpdate(product);
        return flag ? new Result(200, "操作成功") : new Result(500, "操作失败");
    }

    @PostMapping("/listPageProducts")
    @ApiOperation("分页查询产品信息")
    public Result listPageProducts(@RequestBody PageProductDTO pageProductDTO){
        PageData<Product> productPageData = productService.listPageProducts(pageProductDTO);
        return new Result(200, "操作成功", productPageData.getData());
    }

    @GetMapping("/add")
    public Result save(){
        return new Result(200, "保存商品成功");
    }

    @PutMapping("/updateStock/{id}")
    public Result<Integer> updateProduct(@PathVariable Integer id){
        int row = productService.updateStock(id);
        return row > 0 ? new Result(200, "修改成功", row) : new Result(500, "修改失败", -1);
    }

    @GetMapping("/createToken")
    @ApiOperation("order页面创建token")
    public Result createToken(){
        //1、工具类生成token
        String token = TokenUtil.creteToken();
        if(token == null) new Result(500, "创建token失败");
        //2将token存在redis
        redisTemplate.opsForValue().set("idempotent:" + token, token);
        //返回token给页面
        return new Result(200, "创建token成功", token);
    }

    @DeleteMapping("/removeProduct/{id}")
    @ApiOperation("删除商品")
    public Result removeProduct(@PathVariable Integer id){
        boolean flag = productService.removeById(id);
        return flag ? new Result(200, "删除成功") : new Result(500, "删除失败");
    }

}
